package com.kyzh.core.utils;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Point;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.kyzh.core.R;
import com.shuyu.gsyvideoplayer.utils.CommonUtil;
import com.shuyu.gsyvideoplayer.utils.Debuger;
import com.shuyu.gsyvideoplayer.utils.NetworkUtils;
import com.shuyu.gsyvideoplayer.video.base.GSYBaseVideoPlayer;
import com.shuyu.gsyvideoplayer.video.base.GSYVideoPlayer;

import moe.codeest.enviews.ENDownloadView;


/**
 * 带封面
 * Created by guoshuyu on 2017/9/3.
 */

public class SampleLiveVideo extends GSYVideoPlayer {

    ImageView mCoverImage;

    String mCoverOriginUrl;

    int  mCoverOriginId = 0;

    int mDefaultRes;

    public SampleLiveVideo(Context context, Boolean fullFlag) {
        super(context, fullFlag);
    }

    public SampleLiveVideo(Context context) {
        super(context);
    }

    public SampleLiveVideo(Context context, AttributeSet attrs) {
        super(context, attrs);
    }


    private TextView tvHot;
    private ImageView ivRefresh;
    @Override
    protected void init(Context context) {
        super.init(context);
        mCoverImage = (ImageView) findViewById(R.id.thumbImage);
        tvHot = (TextView) findViewById(R.id.tvHot);
        ivRefresh = (ImageView) findViewById(R.id.ivRefresh);
        if (mThumbImageViewLayout != null &&
                (mCurrentState == -1 || mCurrentState == CURRENT_STATE_NORMAL || mCurrentState == CURRENT_STATE_ERROR)) {
            mThumbImageViewLayout.setVisibility(VISIBLE);
        }
        ivRefresh.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                startPlayLogic();
            }
        });
        setViewShowState(mTopContainer, VISIBLE);
        setViewShowState(mBottomContainer, VISIBLE);
        setViewShowState(mStartButton, GONE);
        cancelDismissControlViewTimer();
    }
    /**
     * 开始播放
     */
    @Override
    public void startPlayLogic() {
        if (mVideoAllCallBack != null) {
            Debuger.printfLog("onClickStartThumb");
            mVideoAllCallBack.onClickStartThumb(mOriginUrl, mTitle, SampleLiveVideo.this);
        }
        prepareVideo();
//        startDismissControlViewTimer();
    }
    @Override
    protected void showWifiDialog() {
        if (!NetworkUtils.isAvailable(mContext)) {
            //Toast.makeText(mContext, getResources().getString(R.string.no_net), Toast.LENGTH_LONG).show();
            startPlayLogic();
            return;
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivityContext());
        builder.setMessage(getResources().getString(R.string.tips_not_wifi));
        builder.setPositiveButton(getResources().getString(R.string.tips_not_wifi_confirm), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                startPlayLogic();
            }
        });
        builder.setNegativeButton(getResources().getString(R.string.tips_not_wifi_cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    @Override
    protected void showProgressDialog(float deltaX, String seekTime, int seekTimePosition, String totalTime, int totalTimeDuration) {

    }

    @Override
    protected void dismissProgressDialog() {

    }

    @Override
    protected void showVolumeDialog(float deltaY, int volumePercent) {

    }

    @Override
    protected void dismissVolumeDialog() {

    }

    @Override
    protected void showBrightnessDialog(float percent) {

    }

    @Override
    protected void dismissBrightnessDialog() {

    }

    @Override
    protected void onClickUiToggle(MotionEvent e) {
        Log.e("TAG", "onClickUiToggle: " );

//
        if((mBottomContainer.getVisibility()==INVISIBLE&&mTopContainer.getVisibility()==INVISIBLE)||(mBottomContainer.getVisibility()==GONE&&mTopContainer.getVisibility()==GONE)){
            Log.e("TAG", "onClickUiToggle:111 "+byStartedClick );
            setViewShowState(mBottomContainer, VISIBLE);
            setViewShowState(mTopContainer, VISIBLE);
            setViewShowState(mBottomProgressBar, VISIBLE);
            setViewShowState(mStartButton, GONE);
            if(byStartedClick){
                startDismissControlViewTimer();
            }
        }else {
            Log.e("TAG", "onClickUiToggle:222 "+mBottomContainer.getVisibility()+ "--"+mTopContainer.getVisibility());
            byStartedClick = true;
            setViewShowState(mBottomContainer, INVISIBLE);
            setViewShowState(mTopContainer, INVISIBLE);
            setViewShowState(mBottomProgressBar, VISIBLE);
            setViewShowState(mStartButton, GONE);
        }
    }

    @Override
    protected void hideAllWidget() {
        Log.e("TAG", "hideAllWidget:  cancelDismissControlViewTimer();  resolveUIState" +byStartedClick);

        if(byStartedClick){
            setViewShowState(mBottomContainer, INVISIBLE);
            setViewShowState(mTopContainer, INVISIBLE);
            setViewShowState(mBottomProgressBar, VISIBLE);
            setViewShowState(mStartButton, GONE);
            cancelDismissControlViewTimer();
        }
    }
    protected void resolveUIState(int state) {
        switch (state) {
            case CURRENT_STATE_NORMAL:
                changeUiToNormal();
                cancelDismissControlViewTimer();
                break;
            case CURRENT_STATE_PREPAREING:
                changeUiToPreparingShow();
                cancelDismissControlViewTimer();
                break;
            case CURRENT_STATE_PLAYING:
                changeUiToPlayingShow();
                cancelDismissControlViewTimer();
                break;
            case CURRENT_STATE_PAUSE:
                changeUiToPauseShow();
                cancelDismissControlViewTimer();
                break;
            case CURRENT_STATE_ERROR:
                changeUiToError();
                break;
            case CURRENT_STATE_AUTO_COMPLETE:
                changeUiToCompleteShow();
                cancelDismissControlViewTimer();
                break;
            case CURRENT_STATE_PLAYING_BUFFERING_START:
                changeUiToPlayingBufferingShow();
                break;
        }
    }
    @Override
    protected void changeUiToNormal() {
        Log.e("TAG", "changeUiToNormal: ");
        cancelDismissControlViewTimer();
        setViewShowState(mTopContainer, VISIBLE);
        setViewShowState(mBottomContainer, INVISIBLE);
        setViewShowState(mStartButton, GONE);
        setViewShowState(mLoadingProgressBar, INVISIBLE);
        setViewShowState(mThumbImageViewLayout, VISIBLE);
        setViewShowState(mBottomProgressBar, INVISIBLE);
        setViewShowState(mLockScreen, (mIfCurrentIsFullscreen && mNeedLockFull) ? VISIBLE : GONE);

        if (mLoadingProgressBar instanceof ENDownloadView) {
            ((ENDownloadView) mLoadingProgressBar).reset();
        }
    }

    @Override
    protected void changeUiToPreparingShow() {
        Log.e("TAG", "changeUiToPreparingShow: " );
        setViewShowState(mTopContainer, VISIBLE);
        setViewShowState(mBottomContainer, VISIBLE);
        setViewShowState(mStartButton, GONE);
        setViewShowState(mLoadingProgressBar, VISIBLE);
        setViewShowState(mThumbImageViewLayout, INVISIBLE);
        setViewShowState(mBottomProgressBar, INVISIBLE);
        setViewShowState(mLockScreen, GONE);

        if (mLoadingProgressBar instanceof ENDownloadView) {
            ENDownloadView enDownloadView = (ENDownloadView) mLoadingProgressBar;
            if (enDownloadView.getCurrentState() == ENDownloadView.STATE_PRE) {
                ((ENDownloadView) mLoadingProgressBar).start();
            }
        }
    }

    @Override
    protected void changeUiToPlayingShow() {
        Log.e("TAG", "changeUiToPlayingShow: " );
        setViewShowState(mTopContainer, VISIBLE);
        setViewShowState(mBottomContainer, VISIBLE);
        setViewShowState(mStartButton, GONE);
        setViewShowState(mLoadingProgressBar, INVISIBLE);
        setViewShowState(mThumbImageViewLayout, INVISIBLE);
        setViewShowState(mBottomProgressBar, INVISIBLE);
        setViewShowState(mLockScreen, (mIfCurrentIsFullscreen && mNeedLockFull) ? VISIBLE : GONE);
        cancelDismissControlViewTimer();
        if (mLoadingProgressBar instanceof ENDownloadView) {
            ((ENDownloadView) mLoadingProgressBar).reset();
        }
    }

    @Override
    protected void changeUiToPauseShow() {
        Debuger.printfLog("changeUiToPauseShow");
        Log.e("TAG", "changeUiToPauseShow: " );
        setViewShowState(mTopContainer, VISIBLE);
        setViewShowState(mBottomContainer, VISIBLE);
        setViewShowState(mStartButton, GONE);
        setViewShowState(mLoadingProgressBar, INVISIBLE);
        setViewShowState(mThumbImageViewLayout, INVISIBLE);
        setViewShowState(mBottomProgressBar, INVISIBLE);
        setViewShowState(mLockScreen, (mIfCurrentIsFullscreen && mNeedLockFull) ? VISIBLE : GONE);

        if (mLoadingProgressBar instanceof ENDownloadView) {
            ((ENDownloadView) mLoadingProgressBar).reset();
        }
        updatePauseCover();
    }

    @Override
    protected void changeUiToError() {

    }

    @Override
    protected void changeUiToCompleteShow() {
        Log.e("TAG", "changeUiToCompleteShow: " );
    }

    @Override
    protected void changeUiToPlayingBufferingShow() {
        Log.e("TAG", "changeUiToPlayingBufferingShow: " );
    }

    public TextView getTvHot(){
        return tvHot;
    }
    public ImageView getIvRefresh(){
        return ivRefresh;
    }

    @Override
    public int getLayoutId() {
        return R.layout.video_layout_live;
    }


    public void loadCoverImage(String url, int res) {
        mCoverOriginUrl = url;
        mDefaultRes = res;
        Glide.with(getContext().getApplicationContext())
                .setDefaultRequestOptions(
                        new RequestOptions()
                                .frame(1000000)
                                .centerCrop()
                                .error(res)
                                .placeholder(res))
                .load(url)
                .into(mCoverImage);
    }

//    播放按键修改
//    @Override
//    protected void updateStartImage() {
//        if(mStartButton instanceof ImageView) {
//            ImageView imageView = (ImageView) mStartButton;
//            if (mCurrentState == CURRENT_STATE_PLAYING) {
//                imageView.setImageResource(R.drawable.video_click_pause_selector);
//            } else if (mCurrentState == CURRENT_STATE_ERROR) {
//                imageView.setImageResource(R.drawable.video_click_play_selector);
//            } else {
//                imageView.setImageResource(R.drawable.video_click_play_selector);
//            }
//        }
//    }
    public void loadCoverImageBy(int id, int res) {
        mCoverOriginId = id;
        mDefaultRes = res;
        mCoverImage.setImageResource(id);
    }

    @Override
    public GSYBaseVideoPlayer startWindowFullscreen(Context context, boolean actionBar, boolean statusBar) {
        GSYBaseVideoPlayer gsyBaseVideoPlayer = super.startWindowFullscreen(context, actionBar, statusBar);
        SampleLiveVideo sampleCoverVideo = (SampleLiveVideo) gsyBaseVideoPlayer;
        if(mCoverOriginUrl != null) {
            sampleCoverVideo.loadCoverImage(mCoverOriginUrl, mDefaultRes);
        } else  if(mCoverOriginId != 0) {
            sampleCoverVideo.loadCoverImageBy(mCoverOriginId, mDefaultRes);
        }
        return gsyBaseVideoPlayer;
    }


    @Override
    public GSYBaseVideoPlayer showSmallVideo(Point size, boolean actionBar, boolean statusBar) {
        //下面这里替换成你自己的强制转化
        SampleLiveVideo sampleCoverVideo = (SampleLiveVideo) super.showSmallVideo(size, actionBar, statusBar);
        sampleCoverVideo.mStartButton.setVisibility(GONE);
        sampleCoverVideo.mStartButton = null;
        return sampleCoverVideo;
    }

    @Override
    protected void cloneParams(GSYBaseVideoPlayer from, GSYBaseVideoPlayer to) {
        super.cloneParams(from, to);
        SampleLiveVideo sf = (SampleLiveVideo) from;
        SampleLiveVideo st = (SampleLiveVideo) to;
        st.mShowFullAnimation = sf.mShowFullAnimation;
    }


    /**
     * 退出window层播放全屏效果
     */
    @SuppressWarnings("ResourceType")
    @Override
    protected void clearFullscreenLayout() {
        if (!mFullAnimEnd) {
            return;
        }
        mIfCurrentIsFullscreen = false;
        int delay = 0;
        if (mOrientationUtils != null) {
            delay = mOrientationUtils.backToProtVideo();
            mOrientationUtils.setEnable(false);
            if (mOrientationUtils != null) {
                mOrientationUtils.releaseListener();
                mOrientationUtils = null;
            }
        }

        if (!mShowFullAnimation) {
            delay = 0;
        }

        final ViewGroup vp = (CommonUtil.scanForActivity(getContext())).findViewById(Window.ID_ANDROID_CONTENT);
        final View oldF = vp.findViewById(getFullId());
        if (oldF != null) {
            //此处fix bug#265，推出全屏的时候，虚拟按键问题
            SampleLiveVideo gsyVideoPlayer = (SampleLiveVideo) oldF;
            gsyVideoPlayer.mIfCurrentIsFullscreen = false;
        }

        if (delay == 0) {
            backToNormal();
        } else {
            postDelayed(new Runnable() {
                @Override
                public void run() {
                    backToNormal();
                }
            }, delay);
        }

    }


    /******************* 下方两个重载方法，在播放开始前不屏蔽封面，不需要可屏蔽 ********************/
//    @Override
//    public void onSurfaceUpdated(Surface surface) {
//        super.onSurfaceUpdated(surface);
//        if (mThumbImageViewLayout != null && mThumbImageViewLayout.getVisibility() == VISIBLE) {
//            mThumbImageViewLayout.setVisibility(INVISIBLE);
//        }
//    }
//
//    @Override
//    protected void setViewShowState(View view, int visibility) {
//        if (view == mThumbImageViewLayout && visibility != VISIBLE) {
//            return;
//        }
//        super.setViewShowState(view, visibility);
//    }
//
//    @Override
//    public void onSurfaceAvailable(Surface surface) {
//        super.onSurfaceAvailable(surface);
//        if (GSYVideoType.getRenderType() != GSYVideoType.TEXTURE) {
//            if (mThumbImageViewLayout != null && mThumbImageViewLayout.getVisibility() == VISIBLE) {
//                mThumbImageViewLayout.setVisibility(INVISIBLE);
//            }
//        }
//    }

    /******************* 下方重载方法，在播放开始不显示底部进度和按键，不需要可屏蔽 ********************/

    protected boolean byStartedClick;

//    @Override
//    protected void onClickUiToggle(MotionEvent e) {
//        if (mIfCurrentIsFullscreen && mLockCurScreen && mNeedLockFull) {
//            setViewShowState(mLockScreen, VISIBLE);
//            return;
//        }
//        byStartedClick = true;
//        super.onClickUiToggle(e);
//
//    }
//
//    @Override
//    protected void changeUiToNormal() {
//        super.changeUiToNormal();
//        byStartedClick = false;
//    }
//
//    @Override
//    protected void changeUiToPreparingShow() {
//        super.changeUiToPreparingShow();
//        Debuger.printfLog("Sample changeUiToPreparingShow");
//        setViewShowState(mBottomContainer, INVISIBLE);
//        setViewShowState(mStartButton, INVISIBLE);
//    }
//
//    @Override
//    protected void changeUiToPlayingBufferingShow() {
//        super.changeUiToPlayingBufferingShow();
//        Debuger.printfLog("Sample changeUiToPlayingBufferingShow");
//        if (!byStartedClick) {
//            setViewShowState(mBottomContainer, INVISIBLE);
//            setViewShowState(mStartButton, INVISIBLE);
//        }
//    }
//
//    @Override
//    protected void changeUiToPlayingShow() {
//        super.changeUiToPlayingShow();
//        Debuger.printfLog("Sample changeUiToPlayingShow");
//        if (!byStartedClick) {
//            setViewShowState(mBottomContainer, INVISIBLE);
//            setViewShowState(mStartButton, INVISIBLE);
//        }
//    }
//
//    @Override
//    public void startAfterPrepared() {
//        super.startAfterPrepared();
//        Debuger.printfLog("Sample startAfterPrepared");
//        setViewShowState(mBottomContainer, INVISIBLE);
//        setViewShowState(mStartButton, INVISIBLE);
//        setViewShowState(mBottomProgressBar, VISIBLE);
//    }
//
//    @Override
//    public void onStartTrackingTouch(SeekBar seekBar) {
//        byStartedClick = true;
//        super.onStartTrackingTouch(seekBar);
//    }
}
